<?php
/**
 * 自自定义函数
 */

//定义全局ret
defined('RET_OK') or define('RET_OK', 0);
defined('RET_ERROR') or define('RET_ERROR', -1);
defined('RET_REFRESH_TOKEN') or define('RET_REFRESH_TOKEN', -1000);
defined('RET_BIND_ACCOUNT') or define('RET_BIND_ACCOUNT', -1001);

defined('MSG_OK') or define('MSG_OK', "OK");
defined('MSG_ERROR') or define('MSG_ERROR', "ERROR");

if (!function_exists('normalize'))
{

    /**normalize 统一返回格式，传递参数个数不同时，按以下逻辑接收
     * 0：返回错误，信息提示"ERROR"
     * 1：返回错误，信息为所传参数1
     * 2：返回错误，参数1为信息，参数2为数据
     * 3: 参数1为结果码，参数2为信息，参数3为数据
     * 4或4以上: 只考虑前3个
     *
     * @param array ...$args
     * @return array
     */
    function normalize(...$args)
    {
        if (!isset($args[2]))
        {
            //参数少于3个时，默认为错误状态。
            $ret = RET_ERROR;
            $msg = isset($args[0]) ? $args[0] : MSG_ERROR;
            $data = isset($args[1]) ? $args[1] : [];
        }
        else
        {
            $ret = $args[0];
            $msg = $args[1];
            $data = $args[2];
        }
        if ($data instanceof \Illuminate\Http\Resources\Json\ResourceCollection || $data instanceof \Illuminate\Http\Resources\Json\JsonResource)
        {
            $data = $data->response()->getData(true);
            if (isset($data['data']) && count($data) == 1)
            {
                //单纯的集合，无分页等其数据
                $data = $data['data'];
            }
        }

        return [
            'ret' => (int)$ret,
            'msg' => (string)$msg,
            'data' => $data,
            'timeuse' => (float)number_format(microtime(true) - LARAVEL_START, 3),
        ];
    }
}

if (!function_exists('api')) {
    function api(...$args) {
        return normalize(...$args);
    }
}

/**
 * 返回链接中附件的key
 *
 * @param $url
 * @return string
 */
function attachmentKey($url)
{
    if (!filter_var($url, FILTER_VALIDATE_URL))
    {
        throw new \InvalidArgumentException("url '$url' 不是有效的URL");
    }
    $parsed = parse_url($url);
    $driver = config('admin.upload.disk');
    if ($driver == 'qiniu') {
        return trim($parsed['path'], "/");
    } elseif ($driver == 'cloudinary') {
        $parts = explode('/', $parsed['path']);
        $key = end($parts);
        if (\Illuminate\Support\Str::contains($key,'.')) {
            $key = strstr($key, '.', true);
        }
        return $key;

    } else {
        throw new \RuntimeException('不支持的云盘驱动');
    }

}

/**
 * 根据key返回链接
 * @param $key
 * @param null $width
 * @param null $height
 * @param array $options
 * @return string
 */
function attachmentUrl($key, $width = null, $height = null, $options = [])
{
    if (empty($key)) {
        return '';
    }
    if (substr($key, 0, 4) === 'http') {
        return $key;
    }
    $driver = config('admin.upload.disk');
    if ($driver == 'cloudinary') {
        if (!empty($options['format'])) {
            $key .= sprintf(".%s", str_replace('image/', '', $options['format']));
            unset($options['format']);
        } elseif (strpos($key, '.')) {
            $key .= substr($key, strrpos($key, '.'));
        }
        if ($width) {
            $options['width'] = $width;
        }
        if ($height) {
            $options['height'] = $height;
        }
        return cloudinary_url($key, $options);
    } else {
        static $disk;
        if (!$disk)
        {
            $disk = \Storage::disk($driver);
        }
        if ($driver == 'qiniu') {
            if ($width || $height)
            {
                $previewOptions = "imageView2/0";
                if ($width)
                {
                    $previewOptions .= "/w/$width";
                }
                if ($height)
                {
                    $previewOptions .= "/h/$height";
                }
                return (string)$disk->imagePreviewUrl($key, $previewOptions);
            }
        }
        return (string)$disk->url($key);
    }

}

/**
 * 返回展示图片的 HTML
 *
 * @param $key
 * @param null $width
 * @param null $height
 * @param string $format
 * @return string
 */
function imageHtml($key, $width = null, $height = null, $format = '')
{
    return sprintf('<a href="%s" target="_blank"><img src="%s" /></a>', attachmentUrl($key), attachmentUrl($key, $width, $height));
}

if (!function_exists('createdAt'))
{
    /**
     * 获取创建时间，过去的时间在一定范围内，显示xx小时前之类，太过久远就直接显示时间
     *
     * @param $time 创建时间
     * @param string $format 太过久远时显示时间的格式，默认Y-m-d H:i
     * @param string $interval “久远”是多久，默认10天
     * @return string
     */
    function createdAt($time, $format = null, $interval = "P1D")
    {
        if (empty($time)) {
            return $time;
        }
        $pivot = \Carbon\Carbon::now()->sub(new \DateInterval($interval));
        $target = $time instanceof \Carbon\Carbon ? $time : \Carbon\Carbon::createFromTimestamp(strtotime($time));
        $diff = $pivot->diff($target);
        //如果时间过于久远（超出 diff 指定的时间），直接显示具体时间
        if ($diff->invert)
        {
            if ($format) {
                return $target->format($format);
            }
            if ($diff->y) {
                return $target->format('Y-m-d H:i');
            }
            return $target->format('m-d H:i');
        }
        return $target->diffForHumans();

    }
}

if (!function_exists('auth_user')) {
    /**
     * 获得当前登录用户
     *
     * @return \App\Models\User|null
     */
    function auth_user() {
        static $user;
        if (!is_null($user)) {
            return $user;
        }
        if (is_module_api()) {
            return $user = \Illuminate\Support\Facades\Auth::guard('api')->user();
        }
        if (is_module_admin()) {
            return $user = \Encore\Admin\Facades\Admin::user();
        }

        return $user = \Illuminate\Support\Facades\Auth::user();

    }
}


if (!function_exists('api_user')) {
    /**
     * 获得当前登录的前端用户
     *
     * @return \App\Models\User|null
     */
    function api_user() {
        static $user;
        if (!is_null($user)) {
            return $user;
        }
        if (is_module_api()) {
            return $user = \Illuminate\Support\Facades\Auth::guard('api')->user();
        }

    }
}

if (!function_exists('admin_user')) {
    /**
     * 获得当前登录的后端用户
     *
     * @return \Encore\Admin\Auth\Database\Administrator|null
     */
    function admin_user() {
        static $user;
        if (!is_null($user)) {
            return $user;
        }
        if (is_module_admin()) {
            return $user = \Encore\Admin\Facades\Admin::user();
        }
    }
}

if (!function_exists('is_module_api')) {
    /**
     * 判断是否为 api 模块
     *
     * @return bool
     */
    function is_module_api() {
        return request()->routeIs('api.*');
    }
}


if (!function_exists('is_module_admin')) {
    /**
     * 判断是否为 admin 模块
     *
     * @return bool
     */
    function is_module_admin() {
        return request()->routeIs('admin.*');
    }
}

if (!function_exists('last_query')) {
    /**
     * 获得上一条 query
     *
     * @return string
     */
    function last_query() {
        $queries = \Illuminate\Support\Facades\DB::connection()->getQueryLog();
        $last = last($queries);
        return json_encode_unicode($last);
    }
}

if (!function_exists('json_encode_unicode')) {
    /**
     * json_encode ，unicode 化中文
     *
     * @param $value
     * @return string
     */
    function json_encode_unicode($value) {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

if (!function_exists('logic_abort')) {
    /**
     * 逻辑中止
     *
     * @param $msg
     * @param array $data
     * @throws \App\Exceptions\HuanbaoException
     */
    function logic_abort($msg, array $data = []) {
        throw new \App\Exceptions\HuanbaoException($msg, $data);
    }
}